package org.dwell.vertx3.server;

import io.vertx.core.Vertx;
import org.dwell.vertx3.protocol.Serializer;
import org.dwell.vertx3.protocol.ServerEvent;

/**
 * Created by Emily on 16/1/13.
 */
public class LoadManager {
    private Vertx vertx;
    private Boolean full = false;

    public LoadManager(Vertx vertx) {
        this.vertx = vertx;
    }

    /**
     * Evaluates whether the server should notify the system to
     * stop route users to it. This is done during heavy load.
     *
     * @param users Number of currently connected users.
     */
    public void manage(Integer users) {
        if (Configuration.LOAD_MAX_USERS <= users && !full) {
            sendBus(Configuration.UPSTREAM, new ServerEvent(ServerEvent.ServerStatus.FULL));
            full = true;
        }

        if (users <= Configuration.LOAD_MAX_USERS - Configuration.LOAD_DELTA_BUFFER && full) {
            sendBus(Configuration.UPSTREAM, new ServerEvent(ServerEvent.ServerStatus.READY));
            full = false;
        }
    }

    private void sendBus(String address, Object message) {
        vertx.eventBus().send(address, Serializer.pack(message));
    }
}
